package com.qihoo.finance.backup.reader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MybatisIteratorBackReader extends IteratorBackReader {

    private final ObjectMapper objectMapper = new ObjectMapper();

    private MybatisBackIterator mybatisBackIterator;

    public void setMybatisBackIterator(MybatisBackIterator mybatisBackIterator) {
        this.mybatisBackIterator = mybatisBackIterator;
    }

    @Override
    public boolean hasNext() {
        final boolean hasNext = mybatisBackIterator.hasNext();
        if (!hasNext) {
            close();
        }
        return hasNext;
    }

    @Override
    public List<String> next() {
        try {
            List<Map<String, Object>> list = mybatisBackIterator.next();
            List<String> r = new ArrayList<>();
            for (Map<String, Object> objectMap : list) {
                r.add(objectMapper.writeValueAsString(objectMap));
            }
            return r;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close() {
        mybatisBackIterator.close();
    }
}
